package com.zxmzy.scaffold.core.utils

import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * @author zhangxiaoming
 * @date 2023/8/31
 * @description
 */
object DateUtil {
    private val MONTH_ARRAY_EN = arrayListOf(
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    )
    private val MONTH_ARRAY_CN = arrayListOf(
        "一月",
        "二月",
        "三月",
        "四月",
        "五月",
        "六月",
        "七月",
        "八月",
        "九月",
        "十月",
        "十一月",
        "十二月"
    )
    private val WEEK_ARRAY_EN =
        arrayListOf("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
    private val WEEK_ARRAY_CN =
        arrayListOf("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")

    /**
     * 获取当前日期
     * yyyy-MM-dd
     */
    fun getNowDate(): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        return sdf.format(Date())
    }

    /**
     * 获取当前完整的日期和时间
     * yyyy-MM-dd HH:mm:ss
     */
    fun getNowDateTime(): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        return sdf.format(Date())
    }

    fun getWeekOfDate(date: Date): String {
        val cal = Calendar.getInstance()
        cal.time = date
        var w = cal.get(Calendar.DAY_OF_WEEK) - 1
        w = if (w < 0) 0 else w
        val locale = LanguageUtil.getCurrentLanguage()
        return if (LanguageUtil.ZH_CN != locale.toString()) {
            WEEK_ARRAY_EN[w]
        } else {
            WEEK_ARRAY_CN[w]
        }
    }

    fun formatTime(time: Long): String {
        return if (time.toString().length <= 10) {// 10位的秒级别的时间戳
            SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss",
                Locale.getDefault()
            ).format(Date(time * 1000))
        } else {
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(time)
        }
    }

    fun format(time: Long, format: String): String {
        val simpleDateFormat = SimpleDateFormat(format, Locale.getDefault())
        val date = Date(time)
        return simpleDateFormat.format(date)
    }

    fun formatToDate(timeText: String, format: String = "yyyy-MM-dd HH:mm:ss"): Long {
        val sdf = SimpleDateFormat(format, Locale.getDefault())
        try {
            val date: Date? = sdf.parse(timeText)
            return date?.time ?: Date().time
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return Date().time
    }
}